{% extends "base_generic.html" %}

{% block content %}
  <div class="card">
    <h1>本地图书馆首页</h1>
    <p>欢迎来到 <em>LocalLibrary</em>，这是一个基于Django的图书馆管理示例网站。</p>
    <h2>动态信息</h2>
    <p>当前馆藏数据：</p>
    <ul>
      <li><strong>图书总数：</strong> <span class="text-success">{{ num_books }}</span></li>
      <li><strong>副本总数：</strong> <span class="text-info">{{ num_instances }}</span></li>
      <li><strong>可借副本：</strong> <span class="text-warning">{{ num_instances_available }}</span></li>
      <li><strong>作者总数：</strong> <span class="text-primary">{{ num_authors }}</span></li>
    </ul>
    <a href="{% url 'books' %}" class="btn btn-main">浏览全部图书</a>
    <a href="{% url 'authors' %}" class="btn btn-main" style="margin-left:12px;">浏览全部作者</a>
    <hr>
    <p class="text-muted">
      您已访问本页 <strong>{{ num_visits }}</strong> 次。
    </p>
  </div>

  <div class="card" style="margin-top: 24px;">
    <h2>与AI数字人作者对话</h2>
    <div id="chat-output" style="height: 250px; overflow-y: auto; border: 1px solid #eee; padding: 15px; border-radius: 8px; background-color: #f9f9f9; margin-bottom: 15px;"></div>
    <div class="input-group">
      <input type="text" id="user-message-input" class="form-control" placeholder="向AI数字人作者提问..."/>
      <span class="input-group-btn">
        <button class="btn btn-primary" type="button" id="send-chat-btn">发送</button>
      </span>
    </div>
  </div>

  <div class="card" style="margin-top: 24px;">
    <h2>获取书籍概要</h2>
    <div class="input-group" style="margin-bottom: 15px;">
      <input type="text" id="book-title-input" class="form-control" placeholder="输入书籍名称，例如：红楼梦"/>
      <span class="input-group-btn">
        <button class="btn btn-main" type="button" id="get-summary-btn">获取概要</button>
      </span>
    </div>
    <div id="summary-output" style="border: 1px solid #eee; padding: 15px; border-radius: 8px; background-color: #f9f9f9; min-height: 100px;"></div>
  </div>

  <script>
    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    let conversationHistory = []; // 用于存储对话历史

    document.getElementById('send-chat-btn').addEventListener('click', function() {
        const userInput = document.getElementById('user-message-input').value;
        if (userInput.trim() === '') return;

        const chatOutput = document.getElementById('chat-output');
        chatOutput.innerHTML += `<p><strong>您:</strong> ${userInput}</p>`;
        document.getElementById('user-message-input').value = '';
        chatOutput.scrollTop = chatOutput.scrollHeight; // 滚动到底部

        // 添加用户消息到历史
        conversationHistory.push({"role": "user", "content": userInput});

        fetch('{% url "chat_with_ai" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify({ message: userInput, history: conversationHistory })
        })
        .then(response => response.json())
        .then(data => {
            if (data.reply) {
                chatOutput.innerHTML += `<p><strong>AI数字人作者:</strong> ${data.reply}</p>`;
                // 添加AI回复到历史
                conversationHistory.push({"role": "assistant", "content": data.reply});
            } else if (data.error) {
                chatOutput.innerHTML += `<p class="text-danger"><strong>错误:</strong> ${data.error}</p>`;
            }
            chatOutput.scrollTop = chatOutput.scrollHeight; // 滚动到底部
        })
        .catch(error => {
            console.error('Error:', error);
            chatOutput.innerHTML += `<p class="text-danger"><strong>网络错误:</strong> 无法连接到AI服务。</p>`;
            chatOutput.scrollTop = chatOutput.scrollHeight; // 滚动到底部
        });
    });

    document.getElementById('book-title-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('get-summary-btn').click();
        }
    });

    document.getElementById('get-summary-btn').addEventListener('click', function() {
        const bookTitle = document.getElementById('book-title-input').value;
        if (bookTitle.trim() === '') return;

        const summaryOutput = document.getElementById('summary-output');
        summaryOutput.innerHTML = `<p class="text-muted">正在获取《${bookTitle}》的概要...</p>`;

        fetch('{% url "get_book_summary" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify({ book_title: bookTitle })
        })
        .then(response => response.json())
        .then(data => {
            if (data.summary) {
                summaryOutput.innerHTML = `<p>${data.summary}</p>`;
            } else if (data.error) {
                summaryOutput.innerHTML = `<p class="text-danger"><strong>错误:</strong> ${data.error}</p>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            summaryOutput.innerHTML = `<p class="text-danger"><strong>网络错误:</strong> 无法连接到AI服务。</p>`;
        });
    });
  </script>
{% endblock %}
